/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 Thales Communications, SA
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */
package org.osami.commons.encryption.internal;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Property;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Validate;
import org.osami.commons.encryption.SymmetricEncryptionService;
import org.osami.commons.encryption.EncryptionException;
import org.osami.commons.encryption.internal.util.IOUtils;
import org.osgi.framework.BundleContext;

/**
 * Provides an implementation for the encryption service
 * @author Marcel Arrufat Arias
 *
 */
@Component
@Provides
public class DefaultSymmetricEncryptionService implements SymmetricEncryptionService {

    /**
     * The secret key.
     */
	private Key key;

    /**
     * Cipher mechanic.
     */
	private Cipher cipher;

    /**
     * Decipher mechanic.
     */
	private Cipher decipher;

    @Property(name = "key.file",
              mandatory = true)
    private String keyFile;

    @Property(name = "cipher.algorithm",
              mandatory = true)
    private String algorithm;

    /**
     * This component's BundleContext.
     */
    private BundleContext bundleContext;

    public DefaultSymmetricEncryptionService(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
    }

    @Validate
    public void start() throws EncryptionException {

        try {

            // Load key
            // -----------------------------------

            byte[] bytes = null;
            // At first, try to load it from File
            File file = new File(keyFile);
            if (file.exists()) {
                try {
                    bytes = IOUtils.getBytesFromFile(file);
                } catch (IOException e) {
                    // Ignored
                }
            }

            if (bytes == null) {
                // Try then from this Bundle's resources
                URL resource = bundleContext.getBundle().getResource(keyFile);
                try {
                    bytes = IOUtils.getBytesFromUrl(resource);
                } catch (IOException e) {
                    // Ignored
                }
            }

            if (bytes == null) {
                throw new EncryptionException("Cannot load the key from File/Resource " + keyFile);
            }
            
            this.key = new SecretKeySpec(bytes, algorithm);

            // Load cipher instances
            // -------------------------------------
            // Encrypt
            cipher = Cipher.getInstance(algorithm);
            cipher.init(Cipher.ENCRYPT_MODE, key);

            // Decrypt
            decipher = Cipher.getInstance(algorithm);
            decipher.init(Cipher.DECRYPT_MODE, key);

        } catch (NoSuchAlgorithmException e) {
            throw new EncryptionException("Invalid algorithm", e);
        } catch (NoSuchPaddingException e) {
            throw new EncryptionException("Invalid padding", e);
        } catch (InvalidKeyException e) {
            throw new EncryptionException("Cannot init cipher (key is invalid)", e);
        }

    }

    public void setKeyFile(String keyFile) {
        this.keyFile = keyFile;
    }

    public void setAlgorithm(String algorithm) {
        this.algorithm = algorithm;
    }

    /**
	 * Decrypts the given array with the previously loaded key
	 */
	public byte[] decrypt(byte[] encryptedByteArray) throws EncryptionException {
        try {
            return decipher.doFinal(encryptedByteArray);
        } catch (IllegalBlockSizeException e) {
            throw new EncryptionException("Cannot decipher array", e);
        } catch (BadPaddingException e) {
            throw new EncryptionException("Cannot decipher array", e);
        }
    }


	/**
	 * Encrypts the given byte array with the previously loaded key
	 */
	public byte[] encrypt(byte[] clearByteArray) throws EncryptionException {
        try {
            return cipher.doFinal(clearByteArray);
        } catch (IllegalBlockSizeException e) {
            throw new EncryptionException("Cannot decipher array", e);
        } catch (BadPaddingException e) {
            throw new EncryptionException("Cannot decipher array", e);
        }
    }

}
